"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { KnowledgeBaseCard } from "@/components/knowledge-base/KnowledgeBaseCard";
import { KnowledgeBase } from "@/types/chat";

// 模拟API调用获取知识库列表
const fetchKnowledgeBases = async (): Promise<KnowledgeBase[]> => {
  // 在实际应用中，这里应该是对API的调用
  await new Promise((resolve) => setTimeout(resolve, 1000)); // 模拟网络延迟

  // 返回模拟数据
  return [
    {
      id: "kb-1",
      name: "产品文档",
      description: "包含所有产品使用手册和技术规格",
      chats: [
        {
          id: "chat-1",
          title: "如何使用API",
          messages: [],
          createdAt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
          updatedAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000),
        },
      ],
    },
    {
      id: "kb-2",
      name: "研究论文",
      description: "AI和机器学习相关研究论文",
      chats: [
        {
          id: "chat-2",
          title: "Transformer架构解析",
          messages: [],
          createdAt: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000),
          updatedAt: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000),
        },
        {
          id: "chat-3",
          title: "大语言模型训练技术",
          messages: [],
          createdAt: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000),
          updatedAt: new Date(Date.now() - 12 * 60 * 60 * 1000),
        },
      ],
    },
    {
      id: "kb-3",
      name: "客户支持",
      description: "常见问题解答和客户支持知识库",
      chats: [],
    },
  ];
};

export default function KnowledgeBasePage() {
  const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const loadKnowledgeBases = async () => {
      try {
        setLoading(true);
        const data = await fetchKnowledgeBases();
        setKnowledgeBases(data);
        setError(null);
      } catch (err) {
        console.error("加载知识库失败:", err);
        setError("无法加载知识库，请稍后再试");
      } finally {
        setLoading(false);
      }
    };

    loadKnowledgeBases();
  }, []);

  const handleDeleteKnowledgeBase = (id: string) => {
    // 这里应该是实际的删除逻辑，包括API调用
    setKnowledgeBases((prev) => prev.filter((kb) => kb.id !== id));
  };

  if (loading) {
    return (
      <div className="flex h-full items-center justify-center">
        <div className="h-8 w-8 animate-spin rounded-full border-4 border-blue-500 border-t-transparent"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex h-full items-center justify-center p-4">
        <div className="text-center text-red-500">{error}</div>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">知识库</h1>
          <p className="text-gray-500 dark:text-gray-400">
            管理您的知识库和文档
          </p>
        </div>
        <Button asChild>
          <Link href="/knowledge-base/create">创建知识库</Link>
        </Button>
      </div>

      {knowledgeBases.length > 0 ? (
        <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
          {knowledgeBases.map((kb) => (
            <KnowledgeBaseCard
              key={kb.id}
              knowledgeBase={kb}
              onDelete={handleDeleteKnowledgeBase}
            />
          ))}
        </div>
      ) : (
        <div className="flex flex-col items-center justify-center rounded-lg border border-dashed p-12 text-center dark:border-gray-700">
          <div className="mb-4 text-4xl">📚</div>
          <h3 className="mb-2 text-xl font-semibold">没有知识库</h3>
          <p className="mb-6 text-gray-500 dark:text-gray-400">
            您还没有创建任何知识库，点击下方按钮创建第一个知识库。
          </p>
          <Button asChild>
            <Link href="/knowledge-base/create">创建知识库</Link>
          </Button>
        </div>
      )}
    </div>
  );
} 